'''
Created on 2011-9-13

@author: Administrator
'''

import SimpleXMLRPCServer
import threading
import Queue
import logging


class RpcRequest:
    name = None
    param = None

def FunGenerator(name, request, respond):
    def HandleRPC(*args): 
        result = [False]
        try:
            r = RpcRequest()
            r.name = name
            r.param = args
            request.put(r)
            
            result = respond.get(block=True, timeout=10)
        except Exception as e:
            result.append(str(e))
        finally:
            return result
    return HandleRPC

class RpcServer():
    server = None
    
    def __init__(self, automationserver):
        self.automationserve = automationserver
        self.server = SimpleXMLRPCServer.SimpleXMLRPCServer(("", 8123), logRequests=logging.getLogger(), bind_and_activate=False)
        self.request = Queue.Queue()
        self.respond = Queue.Queue()
        self.request_fun_list = {}
        self.thread = None
        
        self.RegisterFun('EnableMichine', self.automationserve.client_manager.SetEnableMachine)
        self.RegisterFun('SetMichineGroup', self.automationserve.client_manager.SetMachineGroup)
        
        self.RegisterFun('updatetestplan', self.automationserve.scheduler.UpdateTaskTemplate)
        self.RegisterFun('disabletestplan', self.automationserve.scheduler.DeleteTaskTemplate)
        self.RegisterFun('excutetaskplan', self.automationserve.scheduler.ExcuteTemplateTask)
        self.RegisterFun('stoptask', self.automationserve.scheduler.TerminatedTask)
        # task flow
        self.RegisterFun('updatetaskflow', self.automationserve.taskflow_manager.UpdataTaskFlowTemplate)
        self.RegisterFun('excutetaskflow', self.automationserve.taskflow_manager.TriggerTaskFlow)
        self.RegisterFun('stopflowtask', self.automationserve.taskflow_manager.TerminatedTaskFlow)
        self.RegisterFun('removetaskflow', self.automationserve.taskflow_manager.RemoveTaskFlow)

        
    def Init(self):
        self.server.allow_reuse_address = False
        self.server.server_bind()
        self.server.server_activate()
        self.Start()
    
    
    def Uninit(self):
        self.server.shutdown()
        logging.info('rpc server shutdown')
        
    def Start(self):
        self.thread = threading.Thread(target=self._MainLoop)
        self.thread.daemon = True
        self.thread.start()

    def _MainLoop(self):
        self.server.serve_forever(poll_interval=0.2)
        
    def HandleRequest(self, param, fun):
        result = False
        message = ''
        try:
            print(param)
            result = fun(*param)
        except Exception as e:
            message = str(e)
            logging.exception('call fun fail')
        finally:
            self.respond.put([result, message])
        
        
    def Loop(self):
        count = self.request.qsize()
        for i in range(count):
            request = self.request.get()
            if request.name not in self.request_fun_list:
                logging.warn('not exits name in fun list')
            fun = self.request_fun_list[request.name]
            self.HandleRequest(request.param, fun)
            
    def RegisterFun(self, name, fun):
        if name == None:
            raise ValueError('name can not be none')
        
        if fun == None:
            raise ValueError('fun can not be none')
        
        if name  in self.request_fun_list:
            raise ValueError('name aleady exits')
        
        self.request_fun_list[name] = fun
        
        self.server.register_function(FunGenerator(name, self.request, self.respond), name)
        
        
